const config = require("./config").redis;
const Ioredis = require("ioredis");

const redis = new Ioredis({
    host: config.host, //ip
    port: config.port, //端口
})


/**
 * 尝试获取锁
 * @param lockKey 锁的键
 * @param lockTimeout 锁的过期时间
 * @returns 锁的值，成功则返回锁的标识，失败则返回 null
 */
async function lock(lockKey, lockTimeout) {
  const lockValue = Date.now().toString();  // 使用时间戳作为锁的值，确保唯一性
  const result = await redis.set(lockKey, lockValue, 'NX', 'PX', lockTimeout);
  return result === 'OK' ? lockValue : null;
}

/**
 * 释放锁
 * @param lockKey 锁的键
 * @param lockValue 锁的值（唯一标识）
 */
async function unlock(lockKey, lockValue) {
  const script = `
    if redis.call('get', KEYS[1]) == ARGV[1] then
      return redis.call('del', KEYS[1])
    else
      return 0
    end
  `;
  await redis.eval(script, 1, lockKey, lockValue);
}

  
module.exports = {
	lock,
  unlock,
  redis
}
